import re
from django.contrib.auth.backends import ModelBackend

from .models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """重写jwt响应数据的方法"""
    return {
       'token': token,
        'user_id': user.id,
        "username": user.username
    }


def get_user_by_account(account):
    """此函数用来动态根据account来查找用户"""
    try:
        if re.match(r'1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except user.DoesNotExist:
        return None

    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """自定义django用户认证类来实现多账号登陆"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """此方法中要根据username或mobile查找user对象，还要校验密码是否正确，并返回user"""

        # 1.根据用户名或手机号渠道user对象
        user = get_user_by_account(username)

        # 2.校验密码是否正确

        if user and user.check_password(password):
            return user

